package com.kehao.leetcode.jzoffer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/7/7 11:11
 */
public class JZSolution050 {
    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int pathSum(TreeNode root, int targetSum) {
        Map<TreeNode, List<Integer>> map = new HashMap<>();
        dfs(root,map);
        ArrayList<Integer> list = new ArrayList<>();
        map.values().forEach(item->list.addAll(item));
        long count = list.stream().filter(i -> i == targetSum).count();
        return (int) count;
    }

    private List<Integer> dfs(TreeNode root, Map<TreeNode, List<Integer>> map) {
        if(root==null){
            return new ArrayList<>();
        }
        ArrayList<Integer> list = new ArrayList<>();
        map.put(root,list);
        list.addAll(dfs(root.left,map).stream().map(i->i+ root.val).collect(Collectors.toList()));
        list.addAll(dfs(root.right,map).stream().map(i->i+ root.val).collect(Collectors.toList()));
        list.add(root.val);
        return list;
    }
}
